/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.breeze.parser;

import com.breeze.dom.IterateTag;
import com.breeze.dom.PropertyTag;
import com.breeze.dom.TextTag;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

/**
 *
 * @author huateng
 */
public class IbatisParser extends DefaultParser {

    public String parse() {
        StringBuilder sb = new StringBuilder();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse("src/test/template.xml");

            Element root = doc.getDocumentElement();
            NodeList list = root.getChildNodes();
            for (int i = 0; i < list.getLength(); i++) {
                Node n = list.item(i);
                if (n instanceof Text) {
                    sb.append(new TextTag(n, this).display());
                } else if (n instanceof Element) {
                    Element e = (Element) n;
                    if ("property".equals(e.getNodeName())) {
                        sb.append(new PropertyTag(e, this).display());
                    } else if ("iterate".equals(e.getNodeName())) {
                        sb.append(new IterateTag(e, this).display());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String res = sb.toString();
        res = res.replaceAll("\\{\\^", "<");
        res = res.replaceAll("\\^\\}", ">");
        return format(parseConfig(res));
    }

    private String format(String str) {
        StringBuilder sb = new StringBuilder();
        int xml_prefix = 0, sql_prefix = -1;
        BufferedReader reader = new BufferedReader(new StringReader(str));
        String line, lineWithWhiteSpace;
        boolean flag, start = false,sqlFlag=false;
        int continiousWhiteSpaceLine = 0;
        try {
            while (reader.ready()) {
                flag = false;
                sqlFlag=false;
                lineWithWhiteSpace = reader.readLine();
                line = lineWithWhiteSpace == null ? null : lineWithWhiteSpace.trim();
                if (line != null && line.length() > 0) {
                    continiousWhiteSpaceLine = 0;
                    start = true;
                    
                    //test
                    if(line.startsWith("select"))
                        System.out.println("testBegin");

                    //'<'开始 是xml 其他是sql语句
                    if (line.startsWith("<")) {
                        sql_prefix = -1;
                        if (line.startsWith("</")) {
                            flag = true;
                        } else if (line.startsWith("<!") || line.startsWith("<?")) {
                            //第一第二句 不做更改
                        } else {
                            //开始语句
                            ++xml_prefix;
                            if (line.indexOf("</") > 0 || line.indexOf("/>") > 0) {
                                //如果在一行结束 改变flag
                                flag = true;
                            }
                        }
                    } else {
                        //sql语句
                        if (sql_prefix < 0) {
                            //起始语句
                            sql_prefix = xml_prefix + 1;
                        } else {
                            if (line.startsWith("from") || line.startsWith("where")) {
                                --sql_prefix;
                            } else {
                                ++sql_prefix;
                                if (line.endsWith(",")) {
                                    sqlFlag=true;
                                }
                            }
                        }
                    }

                    if (sql_prefix < 0) {
                        //xml语句输出
                        //输出 前缀
                        for (int i = 0; i < xml_prefix - 1; i++) {
                            sb.append("    ");
                        }
                        sb.append(line).append("\n");

                        if (flag)//在一行已经结束
                        {
                            --xml_prefix;
                        }
                    } else {
                        //sql
                        for (int i = 0; i < sql_prefix - 1; i++) {
                            sb.append("    ");
                        }
                        sb.append(line).append("\n");
                        if(sqlFlag)
                            --sql_prefix;
                    }

                } else {
                    continiousWhiteSpaceLine++;
                    if (continiousWhiteSpaceLine > 3) {
                        break;
                    }
                    if (start) {
                        sb.append("\n");
                    }
                }
            }
            return sb.toString();
        } catch (IOException ex) {
            Logger.getLogger(IbatisParser.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
